<template>
  <el-checkbox-group v-bind="$attrs" :size="size">
    <slot>
      <template v-if="checkType === 'el-checkbox-button'">
        <el-checkbox-button
          v-for="(item, index) in optionSourceData"
          v-bind="item"
          :key="index"
          :value="item[optionsProps.value]"
          :border="border"
          :disabled="item[optionsProps.disabled]"
        >
          <slot :name="item.slot" v-bind="item"> {{ item[optionsProps.label] }} </slot></el-checkbox-button
        >
      </template>
      <template v-else>
        <el-checkbox
          v-for="(item, index) in optionSourceData"
          v-bind="item"
          :is="checkType"
          :key="index"
          :value="item[optionsProps.value]"
          :border="border"
          :disabled="item[optionsProps.disabled]"
        >
          <slot :name="item.slot" v-bind="item"> {{ item[optionsProps.label] }} </slot></el-checkbox
        >
      </template>
    </slot>
  </el-checkbox-group>
</template>

<script setup lang="ts" name="OyCheckboxCode">
import { computed, ref, watch } from 'vue'
import type { PropType } from 'vue'
import type { OptionsProps, CheckboxItem } from './checkbox'
import type { CodeOption } from '@/types/components'
import { apiQueryCodeitem } from '@/api/common'
const checkProps = defineProps({
  type: {
    type: String as PropType<'check' | 'button'>,
    validator: (value: string) => ['check', 'button'].includes(value),
    default: 'check',
  },
  // 小代码配置
  codeOption: {
    type: Object as PropType<CodeOption>,
    default: () => {
      return {
        codesetCode: '', // 代码分类编号
      }
    },
  },
  options: {
    type: Array as PropType<CheckboxItem[]>,
    default: () => [],
  },
  size: {
    type: String as PropType<'large' | 'default' | 'small'>,
    validator: (value: string) => ['large', 'default', 'small'].includes(value),
    default: 'default',
  },
  border: {
    type: Boolean,
    default: false,
  },
  props: {
    type: Object,
    default: () => ({}),
  },
})
const checkType = computed(() => {
  const obj = {
    check: 'el-checkbox',
    button: 'el-checkbox-button',
  }
  return obj[checkProps.type] ?? 'el-checkbox'
})
// 是否使用小代码
const isCodeOption = computed(() => {
  return !!checkProps.codeOption.codesetCode
})
const optionsProps = ref<OptionsProps>({
  ...{
    value: isCodeOption.value ? 'itemCode' : 'value',
    label: isCodeOption.value ? 'itemCname' : 'label',
    disabled: 'disabled',
  },
  ...checkProps.props,
})
const optionSourceData = ref(checkProps.options)

const inintOptsData = (obj) => {
  apiQueryCodeitem(obj).then((res) => {
    if (res.data.success) {
      optionSourceData.value = res.data.data
    }
  })
}
// 监听小代码是否配置，如果配置了则从接口获取optionsData数据
watch(
  () => isCodeOption.value,
  (newValue) => {
    if (newValue) {
      inintOptsData(checkProps.codeOption)
    }
  },
  { immediate: true, deep: true }
)
</script>
